package ioStream.file.nodeStream.characterStream;

import org.junit.jupiter.api.Test;

import java.io.FileReader;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description:字符输入流学习
 * User:22954
 * Date:2024-03-15
 * Time:16:08
 */
@SuppressWarnings("all")
public class FileReader_ {
    /*
    FileReader extends InputStreamReader extends Reader
    FileReader所有方法继承父类InputStreamReader继承/实现抽象父类Reader
    int read() throws IOException  读取单个字符,返回读取的字符(ASCII值)，如果已到达流的末尾，则为-1
    int read(char[] cbuf) throws IOException  将字符读取到数组中,返回读取的字符数，如果已到达流的末尾，则为-1
     */
    @Test
    public void readFile1() {//int read() 读取单字符,效率低
        String filePath = "f:/Test/NewFile3.txt";
        FileReader fileReader = null;
        int readData = 0;
        try {
            fileReader = new FileReader(filePath);
            while ((readData = fileReader.read()) != -1) {
                System.out.print((char)readData);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    @Test
    public void readFile2() {//int read(char[] cbuf) 按设定字符数读取,效率高
        String filePath = "f:/Test/NewFile3.txt";
        FileReader fileReader = null;
        char[] buf = new char[6];
        try {
            fileReader = new FileReader(filePath);
            while (fileReader.read(buf) != -1) {
                System.out.print(buf);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    @Test
    public void readFile3() {
        String filePath = "f:/Test/NewFile3.txt";
        FileReader fileReader = null;
        char[] buf = new char[5];
        int readln = 0;
        try {
            fileReader = new FileReader(filePath);
            while ((readln = fileReader.read(buf)) != -1) {
                System.out.print(new String(buf, 0, readln));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
